#include "memoryPool.h"
#include <cstring>

MemoryPool::MemoryPool()
{
    m_blockHead = nullptr;
    m_nodeHead = nullptr;
}

MemoryPool::~MemoryPool()
{
    while (m_blockHead != NULL)
    {
        Block *delBlock = m_blockHead;
        m_blockHead = m_blockHead->next;
        delete delBlock;
        delBlock = nullptr;
    }
}

// 分配空间
void *MemoryPool::Allocate()
{
    // 没有多余空间
    if (m_nodeHead == nullptr)
    {
        Block *newBlock = new Block;
        // 清理脏数据
        memset(newBlock, 0, sizeof(Block));

        for (int idx = 0; idx < NODE_CNT - 1; idx++)
        {
            newBlock->node[idx].next = &(newBlock->node[idx + 1]);
        }

        // 最后一个小内存块需要单独处理
        newBlock->node[NODE_CNT - 1].next = nullptr;

        // 头插
        newBlock->next = m_blockHead;
        m_blockHead = newBlock;

        // 维护连接
        m_nodeHead = &(newBlock->node[0]);
    }

    auto ptr = m_nodeHead;
    // 清除脏数据
    memset(ptr, 0, sizeof(UseNode));
    m_nodeHead = m_nodeHead->next;
    return ptr;
}

// 释放空间
void MemoryPool::free(void *ptr)
{
    UseNode *node = static_cast<UseNode *>(ptr);
    // 清除脏数据
    memset(ptr, 0, sizeof(UseNode));

    node->next = m_nodeHead;
    m_nodeHead = node;
}
